package com.nopay.dxdwphone.net;

import android.content.Intent;
import com.azhon.basic.utils.ActivityManagerUtils;
import com.blankj.utilcode.util.SPUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import com.nopay.dxdwphone.App;
import com.nopay.dxdwphone.Constants;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * author：jun
 * date：2021/11/8
 */
public class LoginStatusInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        String deviceId = SPUtils.getInstance().getString(Constants.SP_DEVICE_ID, "");
        builder.header("deviceId", deviceId);
        Response response = chain.proceed(builder.build());

        ResponseBody body = response.body();
        if (body != null && body.contentType() != null) {
            String result = body.string();
            try {
                JSONObject jsonObject = new JSONObject(result);
                if(!jsonObject.isNull("code")) {
                    int code = jsonObject.getInt("code");
                    if(code == 401) {
                        ActivityManagerUtils.getInstance().exitAllActivity();
                        Intent intent = new Intent("cn.cn.myvisualphone.LOGIN");
                        App.getInstance().getApplicationContext().startActivity(intent);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ResponseBody responseBody = ResponseBody.create(body.contentType(), result);
            return response.newBuilder().body(responseBody).build();
        } else {
            return response;
        }
    }
}
